package com.qixia.upload.config;

import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;


@Configuration
@tk.mybatis.spring.annotation.MapperScan(basePackages = "com.qixia.upload.dao.mapper", sqlSessionFactoryRef = "firstSqlSessionFactory")
public class DataSourceFirst {

    @Primary
    @Bean(name = "firstDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.hikari.first")
    public DataSource firstDataSource() {
        return new HikariDataSource();
    }

    @Primary
    @Bean(name = "firstSqlSessionFactory")
    public SqlSessionFactory firstSqlSessionFactory() throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(firstDataSource());
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:com/qixia/upload/dao/mapper/*.xml"));
        return bean.getObject();
    }

    @Primary
    @Bean(name = "firstDataSourceTransactionManager")
    public DataSourceTransactionManager firstDataSourceTransactionManager() {
        return new DataSourceTransactionManager(firstDataSource());
    }


}
